<script setup lang="ts">
import type { CustomDialogInstance } from '@/types'
import useAnnexReports from './composable'

const props = defineProps<{
  toolId: number
  toolCode: string
  toolName: string
}>()

const emits = defineEmits<{
  (e: 'afterClose'): void
}>()
const dialogRef = ref<CustomDialogInstance>()
const {
  loading,
  tableData,
  getLists,
  deleteAnnexRecord,
  preview,
  pagination,
  downloadPDF,
} = useAnnexReports()

async function download(row: any) {
  if (row.fileUrl && row.fileName) {
    downloadPDF(row.fileUrl, row.fileName)
  }
}
async function remove(row: any) {
  row.id && deleteAnnexRecord(row.id)
}

function getTableData() {
  if (props.toolId)
    getLists(props.toolId)
}

async function onOpen() {
  pagination.pageNumber = 1
  pagination.pageSize = 10
  await nextTick()
  getTableData()
}

function onClose() {
  emits('afterClose')
}

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="查看报告"
    :show-footer="false" :need-saving="false" :no-max-height="true"
    @open="onOpen"
    @close="onClose"
  >
    <div class="flex items-center p-3">
      <span class="text-placeholder">计量器具编号：</span>
      <span>{{ toolCode }}</span>
      <span class="text-placeholder ml-8">计量器具名称：</span>
      <span>{{ toolName }}</span>
    </div>
    <div v-loading="loading" class="h-sm">
      <ElTable :data="tableData" class="custom-table-class" height="100%">
        <template #empty>
          <TableEmpty />
        </template>
        <ElTableColumn label="文件名称" prop="fileName">
          <template #default="{ row }">
            <ElLink type="primary" @click="preview(row.fileUrl)">
              {{ row.fileName }}
            </ElLink>
          </template>
        </ElTableColumn>
        <ElTableColumn label="上传时间" prop="creationTime" />
        <ElTableColumn label="上传人" prop="creationName" />
        <ElTableColumn label="操作" prop="id" fixed="right" width="160px" align="center">
          <template #default="{ row }">
            <ElButton type="primary" text bg size="small" @click="() => download(row)">
              下载
            </ElButton>
            <ElButton type="danger" text bg size="small" @click="() => remove(row)">
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <ListsPagination
      v-model:page-num="pagination.pageNumber"
      v-model:page-size="pagination.pageSize"
      class="justify-end"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      @current-change="getTableData"
      @size-change="getTableData"
    />
  </CustomDialog>
</template>
